import { Component, OnInit, ViewChild, ChangeDetectorRef, Output, Inject, EventEmitter, forwardRef, ChangeDetectionStrategy } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { NzModalService } from 'ng-zorro-antd';
import { path } from '../../../../path.config';
import { FileUploader } from '../../../../../lib/ng2-file-upload';
import { AppComponent } from '../../../../app.component';

import { masterService } from '../../../../../lib/master.service';
import { saveVarService } from '../../../../../lib/saveVar.service';
import { GridComponent } from '../list/grid.component';
import * as moment from 'moment';
import * as $ from 'jquery';
@Component({
    selector: 'voucher-batch-create-form',
    styleUrls: ['./create.component.css'],
    templateUrl: './create.component.html',
    providers: [forwardRef(() => GridComponent), saveVarService, forwardRef(() => AppComponent)]
})
export class VoucherBatchCreateComponent implements OnInit {
    @ViewChild('newVoucherBatch') public newVoucherBatch: ModalDirective;

    @Output() voucherBatchAdd = new EventEmitter<any>();

    // 获取优惠券模板
    private listVoucherTemplate = path.voucherManage.voucherBatch.listVoucherTemplate;
    // 创建优惠券批量发送
    private createBatch = path.voucherManage.voucherBatch.createBatch;
    // 检查券编号前缀
    public checkPrefix = path.voucherManage.voucherBatch.checkPrefix;
    // 上传文件
    private addFileItem = path.imagesUpload.apiUrl;

    public item = {
        prefix: '',
        startIdentifier: '',
        templateId: '',
        startTime: '',
        endTime: '',
        activedTime: '',
        autoJobTime: '',
        enabled: '',
        description: '',
        filePath: ''
    };

    public templates: Array<any> = [];
    private btnEnabled: any = 1;

    constructor(public _masterService: masterService,
        public _saveVar: saveVarService,
        public cdRef: ChangeDetectorRef,
        public confirmServ: NzModalService,
        @Inject(forwardRef(() => GridComponent)) public grid: GridComponent,
        @Inject(forwardRef(() => AppComponent)) public app: AppComponent) { }

    ngOnInit() {
        // get传入的参数
        let urlObject = {
            pageSize: 999,
            pageIndex: 1,
        };
        // 优惠券模板列表
        this._masterService.getData(this.listVoucherTemplate, urlObject)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.templates = res.data;
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息： ' + res.errorMessage);
                }
            });
    }

    // 上传excel对象
    public excelUploader: FileUploader = new FileUploader({
        url: this.addFileItem,
        method: 'post',
        itemAlias: 'uploadedFile'
    })

    // 新建保存
    public saveAdd() {
        this.item.startTime = $('#startTime').val() + '';
        this.item.endTime = $('#endTime').val() + '';
        // 前端验证
        if (this.item.prefix === '') {
            this.app.toastWarning('请填写券编号前缀！');
            return;
        } else if (this.item.startIdentifier === '') {
            this.app.toastWarning('请填写开始标识！');
            return;
        } else if (this.item.templateId === '') {
            this.app.toastWarning('请选择优惠券模板！');
            return;
        } else if (this.item.startTime === '' || this.item.endTime === '') {
            this.app.toastWarning('请选择有效期区间！');
            return;
        } else if (this.item.startTime > this.item.endTime) {
            this.app.toastWarning('结束时间不得小于开始时间！');
            return;
        } else if (this.item.activedTime === '') {
            this.app.toastWarning('请选择激活日期！');
            return;
        } else if (!(/(^[1-9]\d*$)/.test(this.item.startIdentifier))) {
            this.app.toastWarning('开始标识请输入大于零的整数！');
            return;
        } else if (this.item.autoJobTime === '') {
            this.app.toastWarning('请输入定时发送时间！');
            return;
        } else if (this.item.filePath === '') {
            this.app.toastWarning('请上传用户模板！');
            return;
        }

        // 检查券编号前缀
        this._masterService.getData(this.checkPrefix, {prefix: this.item.prefix})
            .subscribe((result) => {
                if (result.statusCode == 200) {
                    if (result.data.count > 0) {
                        this.app.toastError('券编号前缀已存在，请更换前缀！');
                    }
                    else {
                        let thisItem = Object.assign({}, this.item)
                        thisItem.activedTime = moment(thisItem.activedTime).format('YYYY-MM-DD HH:mm:ss')
                        thisItem.autoJobTime = moment(thisItem.autoJobTime).format('YYYY-MM-DD HH:mm:ss')

                        this._masterService.postData(this.createBatch, thisItem)
                            .subscribe(res => {
                                if (res.statusCode == 200) {
                                    this.app.toastSuccess('提交成功，请等待发放！');
                                    this.closeModal();
                                    this.voucherBatchAdd.emit();
                                } else {
                                    this.app.toastError('错误信息: ' + res.errorMessage);
                                }
                            })
                    }
                } else {
                    this.app.toastError('错误信息: ' + result.errorMessage);
                }
            })
    }

    // 上传
    uploadFile() {
        this.btnEnabled = 0;
        let that = this;
        let thisItem = that.excelUploader.queue[that.excelUploader.queue.length - 1];
        if (thisItem == undefined) {
            this.app.toastWarning("请选择excel文件！");
            return;
        }

        // 上传文件后缀并验证
        let suffix = thisItem.some.name.substr(thisItem.some.name.lastIndexOf('.') + 1)
        if (suffix != 'xlsx') {
            this.app.toastWarning('请上传excel格式文件');
            return;
        }

        thisItem.withCredentials = false;
        // 成功回调
        thisItem.onSuccess = function (response, status, headers) {
            // 上传文件成功
            if (status == 200) {
                // 上传文件后获取服务器返回的数据
                let tempRes = JSON.parse(response);
                that.item.filePath = tempRes.data.url[0];
                that.excelUploader.queue = [];
                that.app.toastSuccess('上传成功！');
                that.btnEnabled = 1;
            } else {
                // 上传文件后获取服务器返回的数据错误
                that.app.toastError('上传失败!');
                that.btnEnabled = 1;
            }
        };

        thisItem.onError = function (response, status, headers) {
            // 错误回调
            that.app.toastError('发生了错误！')
            that.btnEnabled = 1;
        };

        thisItem.upload(); // 开始上传
    }

    closeModal() {
        this.newVoucherBatch.hide();
        // 提交完成后清空新建框
        this.item = {
            prefix: '',
            startIdentifier: '',
            templateId: '',
            startTime: '',
            endTime: '',
            activedTime: '',
            autoJobTime: '',
            enabled: '',
            description: '',
            filePath: '',
        };

        this.excelUploader.queue = [];
        $('#startTime').val('');
        $('#endTime').val('');
        $("#excelUploader").val('');
    }
}